package com.an.vhr.service;

import com.an.vhr.bean.Hr;
import com.an.vhr.mapper.HrMapper;
import com.an.vhr.mapper.HrRoleMapper;
import com.an.vhr.utils.HrUtils;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.annotation.Resource;
import java.util.List;

/**
 * @Author: an1089
 **/
@Service
public class HrService implements UserDetailsService {
    @Resource
    HrMapper hrMapper;

    @Resource
    HrRoleMapper hrRoleMapper;



    @Override
    public UserDetails loadUserByUsername(String s) throws UsernameNotFoundException {
        Hr hr = hrMapper.loadUserByUsername(s);
        if(hr == null){
            throw new UsernameNotFoundException("该用户在系统中不存在！");
        }
        hr.setRoles(hrMapper.getRoleById(hr.getId()));
        return hr;
    }

    public List<Hr> getAllHrs(String keyWord) {
        return hrMapper.getAllHrs(HrUtils.getCurrentHr().getId(), keyWord);
    }

    public Integer updateHr(Hr hr) {
        return hrMapper.updateByPrimaryKeySelective(hr);
    }

    @Transactional
    public boolean updateHrRole(Integer hrid, Integer[] rids) {
        hrRoleMapper.deleteByHrid(hrid);
        return hrRoleMapper.insertRoleByHrid(hrid,rids) == rids.length;
    }

    public Integer deleteHrById(Integer id) {
        return hrMapper.deleteByPrimaryKey(id);
    }

    public List<Hr> getAllHrsExceptCurrent(Integer id) {
        return hrMapper.getAllHrsExceptCurrent(id);
    }

    public Integer updateHrPassword(String oldPass, String newPass, String hrid) {

        Hr hr = hrMapper.selectByPrimaryKey(Integer.valueOf(hrid));
        BCryptPasswordEncoder encoder = new BCryptPasswordEncoder();
        if(!encoder.matches(oldPass,hr.getPassword())){
            return 2;
        }
        hr.setPassword(encoder.encode(newPass));
        return hrMapper.updateByPrimaryKeySelective(hr);
    }

    public Integer updateHrUserFace(String upload, Integer id) {
        return hrMapper.updateHrUserFace(upload,id);
    }
}
